import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { useForm, FormProvider } from 'react-hook-form';
import Field from './Field';
import s from './Form.module.css';

function Form({
	className,
	defaultValues,
	resolver,
	mode,
	reValidateMode,
	criteriaMode,
	onSubmit,
	form,
	children,
}) {
	const defaultForm = useForm({
		defaultValues,
		resolver,
		mode,
		reValidateMode,
		criteriaMode,
	});
	const methods = form || defaultForm;

	return (
		<FormProvider {...methods}>
			<form
				className={cn(className, s.form)}
				onSubmit={methods.handleSubmit(onSubmit)}
			>
				{children}
			</form>
		</FormProvider>
	);
}

Form.propTypes = {
	className: PropTypes.string,
	resolver: PropTypes.object,
	defaultValues: PropTypes.object,
	mode: PropTypes.string,
	reValidateMode: PropTypes.string,
	criteriaMode: PropTypes.string,
	form: PropTypes.object,
	onSubmit: PropTypes.func.isRequired,
	children: PropTypes.node.isRequired,
};
Form.defaultProps = {
	className: s.form,
	mode: 'onBlur',
	reValidateMode: 'onChange',
	criteriaMode: 'firstError',
	onSubmit: x => x,
};

export default Form;
export { Field };
